<script setup>
import { ref, computed, watch } from 'vue'
import BaseChart from '@/components/chart/BaseChart.vue'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { useAreaStore } from '@/stores/area'
import { useCompanyStore } from '@/stores/company'
import { getAreaReportApi } from '@/api/area'
import dayjs from 'dayjs'

const props = defineProps({
    title: {
        type: String,
        default: '区域用电趋势'
    },
    height: {
        type: String,
        default: '230px'
    }
})

const areaStore = useAreaStore()
const companyStore = useCompanyStore()

// 趋势图数据和时间控制
const chartTimeRange = ref(null)
const chartData = ref([])
const selectedArea = ref(null)

// 监听区域变化
watch(() => areaStore.areas, () => {
    if (areaStore.areas.length > 0) {
        selectedArea.value = areaStore.areas[0].id
    }
}, {
    immediate: true
})

// 获取单个区域趋势数据
async function getAreaData() {
    if (!selectedArea.value || !chartTimeRange.value) return

    try {
        let res = await getAreaReportApi({
            id: selectedArea.value,
            ...chartTimeRange.value,
            type: 2
        })

        if (res.aggregated_data) {
            chartData.value = res.aggregated_data
                .filter((item) => Array.isArray(item) && item.length > 0)
                .map(item => {
                    let formatStr = 'YYYY-MM-DD'
                    switch (chartTimeRange.value?.interval) {
                        case 'day':
                            formatStr = 'MM-DD'
                            break
                        case 'month':
                            formatStr = 'YYYY-MM'
                            break
                        case 'year':
                            formatStr = 'YYYY'
                            break
                        case 'quarter':
                            formatStr = 'Q季度'
                            break
                    }

                    const value = item.reduce((acc, cur) => {
                        const usedValue = cur && typeof cur.Used !== 'undefined' ? Number(cur.Used) : 0;
                        return acc + usedValue;
                    }, 0).toFixed(2)

                    return {
                        time: dayjs(item[0].StartTime).format(formatStr),
                        timestamp: dayjs(item[0].StartTime).valueOf(),
                        value: value
                    }
                })
                .filter(item => Number(item.value) > 0)
                .sort((a, b) => a.timestamp - b.timestamp)
        }
    } catch (error) {
        console.error('获取区域用电趋势数据失败:', error)
        chartData.value = []
    }
}

// 监听趋势图数据变化
watch([() => selectedArea.value, () => chartTimeRange.value], getAreaData, { immediate: true })

// 趋势图配置
const chartOptions = computed(() => ({
    xAxisData: chartData.value?.map(item => item.time) || [],
    yAxisUnit: 'kwh',
    series: [
        {
            name: '用电量',
            type: 'line',
            data: chartData.value?.map(item => item.value) || [],
        }
    ],
    customColors: ['#409EFF', '#909399']
}))
</script>

<template>
    <div class="card-header">
        <span>{{ title }}</span>
        <div class="right-content">
            <el-select style="width: 35%;" filterable size="small" v-model="selectedArea">
                <el-option v-for="area in areaStore.areas" :key="area.id" :label="area.name"
                    :value="area.id"></el-option>
            </el-select>
            <CustomDateRadio :isFragmentation="true" @update:modelValue="chartTimeRange = $event"></CustomDateRadio>
        </div>
    </div>
    <BaseChart :options="chartOptions" :height="height" />
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.right-content {
    display: flex;
    align-items: center;
    gap: 8px;
}
</style>